<template>

  <el-container class="layout-container-demo" style="height: 900px">
    <el-aside  id="aside"  :style="{ width: asideWidth + 'px'}" >   <!-- 动态限制宽度,加了就会有下拉的箭头 -->
       <el-scrollbar >   <!-- 侧边栏滑动条 --> 
    
           <el-menu v-for="(item,menu) in menuItems " :default-active="activeIndex" class="el-menu-vertical-demo"   :collapse="isCollapse" :collapse-transition="false" > <!--:collapse-transition="false" 关掉折叠过度效果,也可以自定义-->
            <!-- 菜单组 -->
            <el-sub-menu  :index="item.index" :key="item.index " v-if="item.menu"  >
                <template #title >
                  <el-icon >
                    <component :is="item.iconClass" /> <!--  动态显示图标 -->
                  </el-icon>
                  <span>  {{ item.label }}</span>
              </template>

             <!-- 子菜单栏 -->
                  <template v-for="child in menuItems"  >
                  <el-sub-menu :index="child.index" :key="child.index"   v-if="child.parent==item.index && child.submenu"  >
                    <template #title >
                    <el-icon  >
                    <component :is="child.iconClass" />  <!--  动态显示图标  -->
                  </el-icon>
                    <span>  {{ child.label }}</span>
                      </template>
                      <!-- 三级子菜单 -->
                      <template v-for="child1 in menuItems" >
                      <el-menu-item :index="child1.index" :key="child1.index" @click=" addTabs(child1)"    v-if="child1.parent==child.index "  >
                        <el-icon  >
                        <component :is="child1.iconClass" />    
                      </el-icon>
                        {{ child1.label }}
                      </el-menu-item>
                        </template> 
                  </el-sub-menu>
                </template>
               
              <!-- 二级子菜单 -->
                  <template v-for="child in menuItems" >
                  <el-menu-item :index="child.index" :key="child.index" @click="addTabs(child)" v-if="child.parent==item.index && !child.submenu "  >
                    <el-icon  >
                    <component :is="child.iconClass" />  <!--   动态显示图标   -->
                  </el-icon>
                    {{ child.label }}
                  </el-menu-item>
              </template>  
      </el-sub-menu>
    </el-menu>
      </el-scrollbar>
    </el-aside>
    <el-container>
      
      <!-- 头部显示区域 -->
      <el-header style="text-align: left; font-size: 15px">
        <div class="toolbar"> 
          <el-radio-group v-model="isCollapse"  >
          <el-radio-button :value="false"@click="zhank()">展开</el-radio-button>
          <el-radio-button :value="true" @click="zhed()">折叠</el-radio-button>
          </el-radio-group>
          <el-dropdown style="text-align: right; font-size: 15px;padding-left: 1100px; ">
            <el-icon style="margin-right: 12px; margin-top: 2px; ">
              <setting />
            </el-icon>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item>注销</el-dropdown-item>
                <el-dropdown-item>退出</el-dropdown-item>
                <el-dropdown-item>更换头像</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          <span>Tom</span>
        </div>
      </el-header>

      <!-- 主页面显示区域 -->
      <el-main style="background-color: beige;">
          <!-- 标签栏 -->
          <el-tabs
            v-model="editableTabsValue"
            type="card"
            ref="tabs"
            closable
            class="demo-tabs"
            @edit="handleTabsEdit"
            @contextmenu.prevent="openMenu"
          >
          <el-tab-pane
            v-for="item in editableTabs"
            :key="item.name"
            :label="item.title"
            :name="item.name"
          >
          <router-view :v-if="isRouteLoaded" :name=item.router></router-view>  
          </el-tab-pane>

 

          <!-- <ul v-show="visible" :style="{left: left + 'px', top: top + 'px'}" class="contextmenu">
            <li @click="closeTabsOnRight">关闭右侧</li>
            <li @click="closeTabsOnLeft">关闭左侧</li>
            <li @click="closeOtherTabs">关闭其它</li>
            <li @click="closeAllTabs">关闭所有</li>
          </ul> -->

  </el-tabs>
  
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item @click="closeTabsOnRight" >关闭右侧</el-dropdown-item>
            <el-dropdown-item @click="closeTabsOnLeft" >关闭左侧</el-dropdown-item>
            <el-dropdown-item @click="closeOtherTabs" >关闭其它</el-dropdown-item>
            <el-dropdown-item @click="closeAllTabs" >关闭所有</el-dropdown-item>
          </el-dropdown-menu>
     
  
      </el-main>
    </el-container> 
  </el-container>
</template> 

<script lang="ts" setup>
import { ref,reactive,onMounted } from 'vue'
// npm install @element-plus/icons-vue 图标全局安装命令
import { Menu as IconMenu, Setting, User, HelpFilled,ChatLineRound,House,Pointer,ChatLineSquare } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router';   // npm install vue-router@4  没有的话安装下
import { RouterView } from 'vue-router';  
import { type TabPaneName } from 'element-plus'
const router = useRouter(); // 获取路由
const isCollapse = ref(false); //控制菜单栏的展开折叠变量
const activeIndex = ref('1');
let asideWidth = ref(180); // 侧边栏的宽度 
const isRouteLoaded = ref(false);  //
 
const activeName = ref('1');
const visible = ref(false); //
const left = ref(0);
const top = ref(0);

const openMenu = (event:any, tab:any) => {
  debugger;
  event.preventDefault();  //‌阻止表单的自动提交‌：当表单尝试提交时，使用preventdefault()可以阻止表单的默认提交行为，从而可以进行自定义的验证或其他处理
  visible.value = true;
  left.value = event.clientX;
  top.value = event.clientY;
};

// 定义用于关闭左侧标签的函数
const closeTabsOnLeft = () => {
  const currentIndex = editableTabs.value.findIndex(tab => tab.name === editableTabsValue.value);
  if (currentIndex!== -1) {
    // 过滤出要保留的标签，即当前标签及右侧的标签
    const remainingTabs = editableTabs.value.filter((_, index) => index >= currentIndex);
    editableTabs.value = remainingTabs;
  }
};

// 定义一个函数用于处理关闭右侧标签的操作
const closeTabsOnRight = () => {
  const currentIndex = editableTabs.value.findIndex(tab => tab.name === editableTabsValue.value);
  if (currentIndex!== -1) {
    // 过滤出要保留的标签，也就是当前标签及左侧的标签
    const remainingTabs = editableTabs.value.filter((_, index) => index <= currentIndex);
    editableTabs.value = remainingTabs;
  }
};

// 定义用于关闭其他标签（除当前激活标签外）的函数
const closeOtherTabs = () => {
  const currentIndex = editableTabs.value.findIndex(tab => tab.name === editableTabsValue.value);
  if (currentIndex!== -1) {
    // 通过过滤，只保留当前激活的标签
    const remainingTabs = editableTabs.value.filter(tab => tab.name === editableTabsValue.value);
    editableTabs.value = remainingTabs;
  }
};

// 定义用于关闭所有标签的函数
const closeAllTabs = () => {
  // 直接将editableTabs.value赋值为空数组，清空所有标签数据
  editableTabs.value = [];
};

 
// 钩子函数，在页面初始化的时候清空标签栏默认的空数组
onMounted(() => {
  editableTabs.value = [];
});

  
//折叠控制边框宽度
function zhed(){
  asideWidth.value = 60;
}

 //折叠控制边框宽度
 function zhank(){
  asideWidth.value = 150;
}
 
//菜单模拟数据
const menuItems = ref([
    { menu:true,  submenu:false,  parent:'',index: '1',  label: '用户管理', iconClass: User, router:''}, 
    { menu:false, submenu:false, parent:'1',index: '1-1', label: '用户列表', iconClass: 'Star' , router:'user' },
    { menu:false, submenu:false, parent:'1',index: '1-2', label: '用户添加', iconClass: 'CirclePlus' , router:'adduser'},
    { menu:false, submenu:true,  parent:'1',index: '1-3', label: '用户组菜单', iconClass: 'CirclePlus' , router:''},
    { menu:false, submenu:false,  parent:'1-3',index: '1-4', label: '用户添加1', iconClass: 'CirclePlus' , router:'UserTest'},
    { menu:false, submenu:false,  parent:'1-3',index: '1-5', label: '用户添加2', iconClass: 'CirclePlus' , router:'user'},
    { menu:false, submenu:false,  parent:'1-3',index: '1-6', label: '用户添加3', iconClass: 'CirclePlus' , router:'adduser'},
    { menu:true, submenu:false, parent:'',index: '2',  label: '订单管理', iconClass: IconMenu, router:'user'},
    { menu:false, submenu:false, parent:'2',index: '2-1', label: '订单列表1', iconClass: 'Search' , router:'UserTest' },
    { menu:false, submenu:false, parent:'2',index: '2-2', label: '订单详情2', iconClass: 'Service' , router:'adduser' },
    { menu:true,  submenu:false,  parent:'',index: '3', label: '商品管理', iconClass: Setting, router:'user'}, 
    { menu:false, submenu:false, parent:'3',index: '3-1', label: '商品列表1', iconClass: 'CirclePlus'  , router:'user'},
    { menu:false, submenu:false, parent:'3',index: '3-2', label: '商品列表2', iconClass: 'CircleCheckFilled' , router:'adduser' },
    { menu:false, submenu:false, parent:'3',index: '3-3', label: '商品列表3', iconClass: 'InfoFilled' , router:'user' },
    { menu:false, submenu:false, parent:'3',index: '3-4', label: '商品列表4', iconClass: 'Crop' , router:'adduser' },
    { menu:false, submenu:false, parent:'3',index: '3-5', label: '商品列表5', iconClass: 'Delete' , router:'user' },
    { menu:false, submenu:false, parent:'3',index: '3-6', label: '商品添加6', iconClass: 'RemoveFilled'  , router:'adduser'},
    { menu:true,  submenu:false,  parent:'',index: '4', label: '会员管理',iconClass: HelpFilled,router:'user' },
    { menu:false, submenu:false, parent:'4',index: '4-1', label: '新增会员1', iconClass: 'CirclePlusFilled' , router:'user' },
    { menu:false, submenu:false, parent:'4',index: '4-2', label: '新增会员2', iconClass: 'Compass' , router:'adduser' },
    { menu:false, submenu:false, parent:'4',index: '4-3', label: '新增会员3', iconClass: 'Warning' , router:'user' },
    { menu:false, submenu:false, parent:'4',index: '4-4', label: '新增会员4', iconClass: 'CircleClose' , router:'adduser' },
    { menu:false, submenu:false, parent:'4',index: '4-5', label: '删除会员5', iconClass: 'Close' , router:'user' },
   
]);

//点击菜单栏编辑标签栏数组
function addTabs(child:any){
  const newTabName = `${++tabIndex}`
    editableTabs.value.push({
      title: child.label,
      name: newTabName,
      router: child.router,
    })
    editableTabsValue.value = newTabName;
    router.push("/main");   // 总路由
}
 
// 标签栏数据
let tabIndex = 2
const editableTabsValue = ref('1')
const editableTabs  = ref([
  {
    title: '',
    name: '',
    router: '',
  },  
])

// 标签增加和删除事件，目前只用删除功能
const handleTabsEdit = (
  targetName: TabPaneName | undefined,
  action: 'remove' | 'add',
  paneName: TabPaneName | undefined,
) => {
  if (action === 'add') {
    const newTabName = `${++tabIndex}`
    editableTabs.value.push({
      title: 'New Tab',
      name: newTabName,
      router: 'New Tab content',
    })
    activeName.value = newTabName
  } else if (action === 'remove') {
    debugger;
    const tabs = editableTabs.value
    let activeName = editableTabsValue.value
    // 用于判断此标签关闭后，下一个该激活哪个页面，自动获取当前页面的下一个，没有就显示上一个
    if (activeName === targetName) {
      tabs.forEach((tab, index) => {
        if (tab.name === targetName) {
          const nextTab = tabs[index + 1] || tabs[index - 1]
          if (nextTab) {
            activeName = nextTab.name
          }
        }
      })
    }
    editableTabsValue.value = activeName
    editableTabs.value = tabs.filter((tab) => tab.name !== targetName)
  }
}


</script>

<style scoped>
.contextmenu {
  margin: 0;
  background: #fff;
  z-index: 3000;
  position: absolute;
  list-style-type: none;
  padding: 5px 0;
  border-radius: 4px;
  font-size: 12px;
  color: #333;
}
.contextmenu li {
  margin: 0;
  padding: 7px 16px;
  cursor: pointer;
}
.contextmenu li:hover {
  background: #eee;
}

.layout-container-demo .el-header {
  position: relative;
  background-color: var(--el-color-primary-light-7);
  color: var(--el-text-color-primary);
}
.layout-container-demo .el-aside {
  color: var(--el-text-color-primary);
  background: var(--el-color-primary-light-8);
}
.layout-container-demo .el-menu {
  border-right: none;
}
.layout-container-demo .el-main {
  padding: 0;
}
.layout-container-demo .toolbar {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  right: 20px;
  width: auto;
}
</style>
